package com.s64.ssm.controller;

import com.s64.ssm.entity.SysUser;
import com.s64.ssm.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;

@Controller
@RequestMapping("/users")
public class UserController {

    @Autowired
    private IUserService userService;

    @GetMapping
    public String getAll(Model model) {
        model.addAttribute("userList", userService.getAll());
        return "user/list";
    }

    @GetMapping("/del")
    public String del(Integer id) {
        userService.del(id);
        return "redirect:/users";
    }

    @GetMapping("/update/{id}")
    public String update(@PathVariable Integer id, Model model) {
        model.addAttribute("user", userService.get(id));
        return "user/update";
    }

    @PostMapping("/update")
    public String update(SysUser user) {
        userService.update(user);
        return "redirect:/users";
    }

    @GetMapping("/add")
    public String add(Model model) {
        SysUser user = new SysUser();
        user.setBirthday(new Date());
        user.setRoleId(3);
        user.setSex(1);
        model.addAttribute("user", user);
        return "user/add";
    }

    @PostMapping("/add")
    public String add(SysUser user) {
        userService.add(user);
        return "redirect:/users";
    }
}
